const fs = require('fs');
const path = require('path');
const {query} = require('./db');

function readSQLDic(){
  let files = fs.readdirSync(path.join(__dirname,'sql'));
  let fileFilter = [];
  for (const item of files) {
    let itemArr = item.split('.');
    if (itemArr.length == 2) {
      let itemMime = itemArr[1];
      let itemName = itemArr[0];
      if (itemMime === 'sql') {
        fileFilter.push(item);
      }
    }
  }
  return fileFilter;
}

function readSQLContent(fileName){
  return fs.promises.readFile(path.join(__dirname,'sql',fileName),'binary');
}

async function exectueSQL(){
  let files = readSQLDic();
  for (const item of files) {
    let content = await readSQLContent(item);
    if (content) {
      let sqlShellList = content.split(';');
      for (const [i,shell] of sqlShellList.entries()) {
        if (shell.trim()) {
          let result = await query(shell);
          if (typeof(result) == 'Error') {
            console.log(`${item}:第${i}条执行失败--------------`);
          }else{
            console.log(`${item}:第${i}条执行成功++++++++++++++`);
          }
        }
      }
    }
  }
  console.log("数据库初始化完成");
}

module.exports = {exectueSQL};